<template>
  <div>
    <div class="avatar">
      <img :src="Avatar" alt="" />
    </div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit" color="#ff5f16"
          >登录</van-button
        >
      </div>
    </van-form>
    <router-view></router-view>
  </div>
</template>
<script>
import Vue from 'vue'
import { Form, Field, Toast } from 'vant'
import Avatar from '@/assets/login.png'
Vue.use(Form)
Vue.use(Field)
Vue.use(Toast)
export default {
  data() {
    return {
      username: '',
      password: '',
      Avatar
    }
  },
  methods: {
    onSubmit(values) {
      // console.log('submit', values) //values是表单插件给我们自动收集的用户名密码组成的对象
      // 对象转字符串
      let str = ''
      let f = ''
      for (const key in values) {
        str += f + key + '=' + values[key]
        f = '&'
      }
      // console.log(str)
      this.$http.post('/users/login', str).then((res) => {
        // console.log(res)
        if (res.code === 1) {
          Toast.success(res.msg)
          // 跳转到我的页面
          this.$router.push('/my')
        }
        Toast.fail(res.msg)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar {
  margin: 79px auto 40px;
  text-align: center;
  height: 60px;
  line-height: 60px;
  img {
    height: 60px;
  }
}
</style>